package com.livedocumentation.client.webservices.comments;

import java.util.Date;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.Window;
import com.livedocumentation.client.GWTEntryPoint;
import com.livedocumentation.client.model.Comment;

public class SaveCommentRequest {

	// http://jsonpfy.livedocumentation.appspot.com/SaveDataService?
	// kind=Comment
	// &fieldsKind=String&fieldsName=description&fieldsValue=Test
	// &fieldsKind=String&fieldsName=projectID&fieldsValue=Projectnection
	// &fieldsKind=String&fieldsName=classPath&fieldsValue=com.projectnection.client.Entities.EntityPage
	// &fieldsKind=String&fieldsName=username&fieldsValue=Alline Watkins
	// &fieldsKind=String&fieldsName=email&fieldsValue=alline.oliveira@gmail.com
	// &fieldsKind=String&fieldsName=facebookUserID&fieldsValue=alline.oliveira
	// &fieldsKind=Date&fieldsName=date&fieldsValue=1313085767484

	private static String url = "http://jsonpfy.livedocumentation.appspot.com/SaveDataService";

	public static void sendPostRequest(final Comment comment) {

		String urlSave = url + "?kind=Comment"
				+ "&fieldsKind=String&fieldsName=description&fieldsValue="
				+ comment.getDescription()
				+ "&fieldsKind=String&fieldsName=projectID&fieldsValue="
				+ comment.getProjectID()
				+ "&fieldsKind=String&fieldsName=classPath&fieldsValue="
				+ comment.getClassPath()
				+ "&fieldsKind=Date&fieldsName=date&fieldsValue="
				+ new Date().getTime();

		if (comment.getFacebookUser() != null) {

			urlSave += "&fieldsKind=String&fieldsName=username&fieldsValue="
					+ comment.getFacebookUser().getFacebookName()
					+ "&fieldsKind=String&fieldsName=email&fieldsValue="
					+ comment.getFacebookUser().getEmail()
					+ "&fieldsKind=String&fieldsName=facebookUserID&fieldsValue="
					+ comment.getFacebookUser().getFacebookID();
		}

		RequestBuilder builder = new RequestBuilder(RequestBuilder.POST,
				urlSave);

		// builder.setRequestData(requestData);

		try {
			Request request = builder.sendRequest(null, new RequestCallback() {

				public void onError(Request request, Throwable exception) {
					Window.alert("Fail: " + exception);
				}

				public void onResponseReceived(Request request,
						Response response) {

					RequestListComments.getJsonpRequest(
							GWTEntryPoint.currentProject.getProjectID(),
							comment.getClassPath());

					if (200 == response.getStatusCode()) {
						// updateTable(asArrayOfStockData(response.getText()));
					} else {
						// displayError("Couldn't retrieve JSON ("
						// + response.getStatusText() + ")");
					}
				}
			});
		} catch (RequestException e) {
			// displayError("Couldn't retrieve JSON");
		}
	}
}
